import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

class ProfileEditPage extends StatefulWidget {
  const ProfileEditPage({super.key});

  @override
  State<ProfileEditPage> createState() => _ProfileEditPageState();
}

class _ProfileEditPageState extends State<ProfileEditPage> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController(text: '学生用户');
  String _selectedStage = '初中';
  String _selectedGrade = '初二'; // 修改为初中年级列表中的有效值
  String _selectedPlan = '提高基础成绩';
  int _learningProgress = 60; // 学习进度百分比
  File? _selectedImage; // 用户选择的头像图片
  final ImagePicker _picker = ImagePicker();

  final List<String> _stages = ['小学', '初中', '高中'];
  final Map<String, List<String>> _grades = {
    '小学': ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级'],
    '初中': ['初一', '初二', '初三'],
    '高中': ['高一', '高二', '高三'],
  };
  final List<String> _plans = ['提高基础成绩', '查漏补缺', '冲刺高分', '保持稳定'];

  @override
  void dispose() {
    _usernameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            if (context.canPop()) {
              context.pop();
            } else {
              context.go('/profile');
            }
          },
        ),
        title: const Text('编辑个人信息'),
        actions: [TextButton(onPressed: _saveProfile, child: const Text('保存'))],
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              _buildAvatarSection(),
              const SizedBox(height: 24),
              _buildUsernameSection(),
              const SizedBox(height: 24),
              _buildStageSection(),
              const SizedBox(height: 24),
              _buildGradeSection(),
              const SizedBox(height: 24),
              _buildProgressSection(),
              const SizedBox(height: 24),
              _buildPlanSection(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAvatarSection() {
    return Center(
      child: Column(
        children: <Widget>[
          Stack(
            children: <Widget>[
              CircleAvatar(
                radius: 50,
                backgroundColor: Theme.of(context).colorScheme.primary,
                backgroundImage:
                    _selectedImage != null ? FileImage(_selectedImage!) : null,
                child:
                    _selectedImage == null
                        ? const Icon(
                          Icons.person,
                          color: Colors.white,
                          size: 50,
                        )
                        : null,
              ),
              Positioned(
                bottom: 0,
                right: 0,
                child: GestureDetector(
                  onTap: _changeAvatar,
                  child: Container(
                    padding: const EdgeInsets.all(4),
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.primary,
                      shape: BoxShape.circle,
                    ),
                    child: const Icon(
                      Icons.camera_alt,
                      color: Colors.white,
                      size: 20,
                    ),
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          TextButton(onPressed: _changeAvatar, child: const Text('更换头像')),
        ],
      ),
    );
  }

  Widget _buildUsernameSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text(
          '用户名',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: _usernameController,
          decoration: const InputDecoration(hintText: '请输入用户名'),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请输入用户名';
            }
            return null;
          },
        ),
      ],
    );
  }

  Widget _buildStageSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text(
          '学段',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 8),
        DropdownButtonFormField<String>(
          value: _selectedStage,
          decoration: const InputDecoration(),
          items:
              _stages.map((stage) {
                return DropdownMenuItem(value: stage, child: Text(stage));
              }).toList(),
          onChanged: (value) {
            setState(() {
              _selectedStage = value!;
              // 确保年级值在新的学段中是有效的
              final newGrades = _grades[value]!;
              if (!newGrades.contains(_selectedGrade)) {
                _selectedGrade = newGrades.first;
              }
            });
          },
        ),
      ],
    );
  }

  Widget _buildGradeSection() {
    final grades = _grades[_selectedStage] ?? [];
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text(
          '年级',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 8),
        DropdownButtonFormField<String>(
          value: _selectedGrade,
          decoration: const InputDecoration(),
          items:
              grades.map((grade) {
                return DropdownMenuItem(value: grade, child: Text(grade));
              }).toList(),
          onChanged: (value) {
            setState(() {
              _selectedGrade = value!;
            });
          },
        ),
      ],
    );
  }

  Widget _buildProgressSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text(
          '学习进度',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 8),
        Column(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text('当前进度: $_learningProgress%'),
                Text('目标: 100%'),
              ],
            ),
            const SizedBox(height: 8),
            Slider(
              value: _learningProgress.toDouble(),
              min: 0,
              max: 100,
              divisions: 20,
              label: '$_learningProgress%',
              onChanged: (value) {
                setState(() {
                  _learningProgress = value.round();
                });
              },
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildPlanSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Text(
          '学习计划',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 8),
        DropdownButtonFormField<String>(
          value: _selectedPlan,
          decoration: const InputDecoration(),
          items:
              _plans.map((plan) {
                return DropdownMenuItem(value: plan, child: Text(plan));
              }).toList(),
          onChanged: (value) {
            setState(() {
              _selectedPlan = value!;
            });
          },
        ),
      ],
    );
  }

  Future<void> _changeAvatar() async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Wrap(
            children: <Widget>[
              ListTile(
                leading: const Icon(Icons.photo_camera),
                title: const Text('拍照'),
                onTap: () async {
                  Navigator.pop(context);
                  await _pickImage(ImageSource.camera);
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library),
                title: const Text('从相册选择'),
                onTap: () async {
                  Navigator.pop(context);
                  await _pickImage(ImageSource.gallery);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _pickImage(ImageSource source) async {
    try {
      final XFile? image = await _picker.pickImage(
        source: source,
        maxWidth: 300,
        maxHeight: 300,
        imageQuality: 80,
      );

      if (image != null) {
        setState(() {
          _selectedImage = File(image.path);
        });
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择图片时出错: $e'), backgroundColor: Colors.red),
      );
    }
  }

  void _saveProfile() {
    if (_formKey.currentState!.validate()) {
      // TODO: 保存用户信息到本地存储或服务器
      print('保存用户信息:');
      print('用户名: ${_usernameController.text}');
      print('学段: $_selectedStage');
      print('年级: $_selectedGrade');
      print('学习进度: $_learningProgress%');
      print('学习计划: $_selectedPlan');
      print('头像: ${_selectedImage?.path ?? '未选择'}');

      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('保存成功！')));

      // 返回上一页
      if (context.canPop()) {
        context.pop();
      } else {
        context.go('/profile');
      }
    }
  }
}
